import { defineStore } from 'pinia'
import {
  deleteUserById,
  postUsersListData,
  newUserData,
  editUserData,
  postPageListData,
  deletePageById,
  newPageData,
  editPageData
} from '@/service/main/system/system'
import useMainStore from '../main'

//获取到的 userList: []是never[]类型,不能拿到数据，需要定义类型
interface ISystemState {
  usersList: any[]
  usersTotalCount: number
  pageList: any[]
  pageTotalCount: number
}

const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    usersList: [],
    usersTotalCount: 0,
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    async postUsersListAction(queryInfo: any) {
      const userListResult = await postUsersListData(queryInfo)

      const { totalCount, list } = userListResult.data
      this.usersList = list
      this.usersTotalCount = totalCount
    },
    async deleteUserByIdAction(id: number) {
      const deleteResult = await deleteUserById(id)
      //删除数据之后重新请求数据列表，重新渲染页面数据

      this.postUsersListAction({ offset: 0, size: 10 })
    },
    async newUserDataAction(userInfo: any) {
      const newResult = await newUserData(userInfo)
      this.postUsersListAction({ offset: 0, size: 10 })
    },
    async editUserDataAction(id: number, userInfo: any) {
      const editResult = await editUserData(id, userInfo)

      //重新请求新数据
      this.postUsersListAction({ offset: 0, size: 10 })
    },
    async postPageListDataAction(pageName: string, queryInfo: any) {
      const pageListResult = await postPageListData(pageName, queryInfo)
      const { list, totalCount } = pageListResult.data
      this.pageList = list
      this.pageTotalCount = totalCount
    },
    async deletePageByIdAction(pageName: string, id: number) {
      const deleteResult = await deletePageById(pageName, id)
      //删除数据之后重新请求数据列表，重新渲染页面数据

      this.postPageListDataAction(pageName, { offset: 0, size: 10 })
      //重新请求新数据,保证创建完新角色之后能够渲染到页面上，提供给其他页面选择
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    async newPageDataAction(pageName: string, pageInfo: any) {
      const newResult = await newPageData(pageName, pageInfo)
      this.postPageListDataAction(pageName, { offset: 0, size: 10 })
      //重新请求新数据,保证创建完新角色之后能够渲染到页面上，提供给其他页面选择
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    async editPageDataAction(pageName: string, id: number, pageInfo: any) {
      const editResult = await editPageData(pageName, id, pageInfo)
      this.postPageListDataAction(pageName, { offset: 0, size: 10 })
      //重新请求新数据,保证创建完新角色之后能够渲染到页面上，提供给其他页面选择
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    }
  }
})
export default useSystemStore
